#include "smfile.h"
#include <QFile>
smFile::smFile(QString file) {
  blockCount = 0;
  openFileName = file;
  fPtr = NULL;
}

void smFile::setBigFileName(QString &name) { openFileName = name; }

void smFile::setReadSize(qint64 size) { blockSize = size; }

void smFile::setSeek(qint64 pos) { currentPos = pos; }

bool smFile::openBigFile(QIODevice::OpenMode mode,
                         QFileDevice::FileHandleFlags handleFlags) {
  bool bRet = false;
  qint64 cnt = 0;
  Q_UNUSED(handleFlags);
  do {
    if (openFileName.isEmpty())
      break;
    setFileName(openFileName);
    bRet = open(mode);
    if (bRet == false) {
      emit sErrorInfo(this->errorString());
    }
    /* 计算count数量,文件大小 */
    cnt = ((this->size() % blockSize) == 0) ? (0) : (1);
    blockCount = (quint64)(this->size() / blockSize) + cnt;

    /* set */
    if (currentPos > this->size() - 1) {
      emit sErrorInfo(QString("seek:Offset exceeds file size."));
    }

    // fPtr = this->map(currentPos, blockSize);
  } while (0);
  return bRet;
}

qint64 smFile::getBlockCount() { return blockCount; }

uchar *smFile::nextSeek(void) {
  uchar *ptr = NULL;
  do {
    if (fPtr != NULL) {
      this->unmap(fPtr);
      fPtr = NULL;
    }
    if (currentPos > this->size() - 1) {
      currentPos -= blockSize;
      break;
    }
    if (currentPos < 0)
      currentPos = 0;

    if (currentPos + blockSize > this->size()) {
      fPtr = this->map(currentPos, this->size());
    } else {
      fPtr = this->map(currentPos, blockSize);
    }

    if (fPtr == NULL)
      break;
    ptr = fPtr;
    currentPos += blockSize;

  } while (0);
  return ptr;
}
uchar *smFile::nextSeek(qint64 pos) {
  uchar *ptr = NULL;
  do {
    if (fPtr != NULL) {
      this->unmap(fPtr);
      fPtr = NULL;
    }
    if (pos > this->size() - 1) {
      break;
    }
    currentPos = pos;
    if (currentPos + blockSize > this->size()) {
      fPtr = this->map(currentPos, this->size());
    } else {
      fPtr = this->map(currentPos, blockSize);
    }
    if (fPtr == NULL)
      break;
    ptr = fPtr;
    currentPos += blockSize;
  } while (0);
  return ptr;
}

void smFile::closeBigFile() {
  if (fPtr != NULL) {
    this->unmap(fPtr);
    fPtr = NULL;
  }
  this->close();
}

uchar *smFile::prevSeek(void) {
  uchar *ptr = NULL;
  do {
    if (fPtr != NULL) {
      this->unmap(fPtr);
      fPtr = NULL;
    }
    if (currentPos < blockSize) {
      currentPos = 0;
    } else {
      currentPos -= blockSize;
    }

    if (currentPos + blockSize > this->size()) {
      fPtr = this->map(currentPos, this->size());
    } else {
      fPtr = this->map(currentPos, blockSize);
    }
    if (fPtr == NULL)
      break;
    ptr = fPtr;
  } while (0);
  return ptr;
}
